<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Address;
use App\Models\Company;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Validator;

class AddressController extends Controller
{
    private $user;
    private $company_id;
    public function __construct()
    {
        if (\Auth::guard('api')->check()) {
            $user = \Auth::guard('api')->user();
            $data = User::find($user->id);
            $this->user = $data;
            $company = Company::find($this->user->company_id);
            $this->company_id = $data->company_id;
        }
    }
    /**
     * 查询所有
     */
    public function all(Request $request)
    {
        $data = Address::where(['status' => 0, 'company_id' => $this->company_id])->orderBy('id', 'desc')->select('id', 'address')->get();
        return $this->respond('get_ok', $data);
    }
    //获取单条记录
    public function get($id)
    {
        $data = Address::find($id);
        if (!empty($data)) {
            return $this->respond('get_ok', $data);
        }
        return $this->respond('get_error');
    }
    //新增保存
    public function add(Request $request)
    {
        $validator = Validator::make($request->all(), Address::$rules, Address::$message);
        if ($validator->fails()) {
            return response()->json(['code' => 500, 'msg' => $validator->errors()->first()]);
        }
        $m = new Address();
        $m->user_id = $this->user->id;
        $m->company_id = $this->company_id;
        $m->address = $request->input('address');
        $result = $m->save();
        if ($result) {
            return $this->respond('add_ok');
        }
        return $this->respond('add_error');
    }
    //更新保存
    public function put(Request $request, $id)
    {
        $m = new Address();
        $model = $m::find($id);
        if (empty($model)) {
            return $this->respond('get_error');
        }
        $validator = Validator::make($request->all(), ['address' => ['required', 'max:20', Rule::unique('addresses')->ignore($id)]], Address::$message);
        if ($validator->fails()) {
            return response()->json(['code' => 500, 'msg' => $validator->errors()->first()]);
        }
        $model->address = $request->input('address');
        $result = $model->save();
        if ($result) {
            return $this->respond('update_ok');
        }
        return $this->respond('update_error');
    }
    //删除
    public function remove($id)
    {
        if (empty($id)) {
            return $this->respond('empty_errorp');
        }
        $m = Address::find($id);
        if (empty($m)) {
            return $this->respond('get_error');
        }
        $m->status = 1;
        $result = $m->save();
        if ($result) {
            return $this->respond('delete_ok');
        }
        return $this->respond('delete_error');
    }
}
